/**
 * Foxit Software Inc.
 * Copyright(C) 2005-2014, all rights reserved.
 * The following code is copyrighted and contains proprietary information
 * and trade secrets of Foxit Software Inc.

 * Description: ImagePageViewRender.js
 * Author: shaojie zhuo
 */
define(function (require, exports, module) {
    require('./ImageEngine.js');
    require('../Common.js');
    require("../Config.js");
    var Config = WebPDF.Config;
    var ImgLazyLoad = require('../ImageLazyLoad.js');
    require('../AjaxRetryManager.js');
    var ImageEngine = WebPDF.ImageEngine;

    /**
     * Enum for error code of requesting page images.
     * @enum
     */
    ImageEngine.GetImageErrorCode = {
        /**
         * Page cannot be display due to display range limitation.
         */
        ERROR_PAGE_DISPLAY_LIMIT : 1,
        /**
         * Create image failed.
         */
        ERROR_CREATE_IMG_FAILED : 2,
        /**
         * Image is being converting.
         */
        ERROR_INPROGRESS : 3
    };

    var ImagePageViewRender = function () {
        var _renderingPageList = {},
            _maxRenderPageIndex = -1,
            _readerApp = null,
            _self = this;

        this.getMaxRenderedPageIndex = function()
        {
            return _maxRenderPageIndex;
        };
        
        this.setReaderApp = function(readerApp){
            _readerApp = readerApp;
        };

        this.getPageImgUrl = function (pageIndex, zoom, isThumb) {
            //always set zoom to 100
            zoom = 100;
            var strZoom = isThumb ? "thumb" : zoom + "";
            var imageUrl = _readerApp.getOptions().url + "image/" + pageIndex + "/" + strZoom;
            imageUrl += "?s3Key=" + _readerApp.getFileID();
            if (_readerApp.isForm()) {
                imageUrl += "&form=true";
            }
            if(_readerApp.isFormMode()){
            	imageUrl += "&formMode=true";
            }
            return imageUrl;
        };

        this.renderPage = function (pageView, retryCount) {           
            if (!pageView || !pageView.isContentCreated() || 
            		(pageView.isPageLoaded() && !pageView.isPageLoadError())) {
                return;
            }
            var pageIndex = pageView.getPageIndex();    
            var bLoadThumbImg = pageView.isThumb();
            if (WebPDF.Environment.mobile) {
            	bLoadThumbImg = bLoadThumbImg || !pageView.isThumbnailLoaded();
            }
            var pageKey = (bLoadThumbImg ? "thumb" : "page") + pageIndex;
            if (retryCount <= 0) {
                console.warn("Maximum number of retries exceeded for render page: " + pageIndex + "; thumb:" + pageView.isThumb());
                _renderingPageList[pageKey] = null;
                return;
            }

            if (!_renderingPageList[pageKey]) {
                var validPageOffset = 1;
                var docView = pageView.getDocView();
                var visiblePageRange = docView.getVisiblePageRange();
                if(pageIndex <= visiblePageRange.begin - validPageOffset
                    || pageIndex >= visiblePageRange.end + validPageOffset){
                    return;
                }
                _renderingPageList[pageKey] = pageView;
                var imageUrl = _self.getPageImgUrl(pageIndex, pageView.getScale(), bLoadThumbImg);
                new ImgLazyLoad(imageUrl, !pageView.isPageLoadError(), _readerApp,pageView, function (curPageView,state) {
                    var bLoadError = false;
                    var bGetPageImgFailed = (state == ImageEngine.GetImageErrorCode.ERROR_CREATE_IMG_FAILED);
                    var bPageImgLimit = (state == ImageEngine.GetImageErrorCode.ERROR_PAGE_DISPLAY_LIMIT);
                    var isInProgress = (state == ImageEngine.GetImageErrorCode.ERROR_INPROGRESS);
                    if(bGetPageImgFailed || bPageImgLimit)  {
                        bLoadError = true;
                    }
                    else if (isInProgress) {
                        if(_maxRenderPageIndex === -1) {
                            _maxRenderPageIndex = 0;
                        }
                        var interval = WebPDF.AjaxRetryManager.getNextPageImageRequestInterval(curPageView.getPageIndex(),
                            _maxRenderPageIndex,docView.getPageCount());
                        _renderingPageList[pageKey] = null;
                        setTimeout(function () { _self.renderPage(curPageView, retryCount - 1); }, interval);
                        return;
                    }
                    _maxRenderPageIndex = curPageView.getPageIndex();

                    _renderingPageList[pageKey] = null;
                    if(!bLoadError) {
                    	$("#" + curPageView.getPageBackgroundImgID()).attr("src", imageUrl);
                        curPageView.show();

                        if(WebPDF.Environment.mobile && !curPageView.isThumb()){
                            if(!curPageView.isThumbnailLoaded()){
                                curPageView.setThumbnailLoaded(true);
                                setTimeout(function () { _self.renderPage(curPageView, Config.defaults.requestRetryCount); }, 50);
                            }
                            else{
                                curPageView.setPageLoaded(true);
                            }
                        }
                        else{
                            curPageView.setPageLoaded(true);
                        }
                    }
                    else
                    {
                        if(WebPDF.Environment.mobile && !curPageView.isThumb()) {
                            curPageView.setThumbnailLoaded(true);
                        }
                        curPageView.setPageLoaded(true);
                        var failedImgUrl = "";
                        if(bGetPageImgFailed) {
                            failedImgUrl = _readerApp.getBaseUrl() + "images/reader/imgFailed.png";
                        }
                        else  {
                            failedImgUrl =  _readerApp.getBaseUrl() + "images/reader/imgLimit.png";
                        }
                        curPageView.showErrorPage(failedImgUrl);
                    }
                    curPageView.setPageLoadError(bLoadError);
                    if(!curPageView.isThumb()) {
                        $(_readerApp).trigger(WebPDF.EventList.PAGE_SHOW_COMPLETE,{pageView:curPageView});
                    }

                }, function (curPageView) {
                    _renderingPageList[pageKey] = null;
                    curPageView.setPageLoaded(true);
                    curPageView.setPageLoadError(true);
                    curPageView.showErrorPage(_readerApp.getBaseUrl() + "images/reader/imgFailed.png");
                    if(!curPageView.isThumb())  {
                        $(_readerApp).trigger(WebPDF.EventList.PAGE_SHOW_COMPLETE,{pageView:curPageView});
                    }
                });
            }
        };
    };

    return ImagePageViewRender;
});